package it.uni.bo.monitoring.queue;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import static it.uni.bo.monitoring.service.StaticFields.QUERY_RAWDATA;

public class LazyRemoveRawData extends Thread {

	private BlockingQueue<byte[]> eqToRemove;
	private SessionFactory factory;
	private Logger l;

	private static final String ERROR_RAWDATA="non riesco a rimuovere il rawdata";
	private static final String ERROR_ROLLING_BACK="error rolling back transaction";
	private static final String INFO_DELETE="elimino in RawData i record";

	public LazyRemoveRawData(BlockingQueue<byte[]> eqToRemove, SessionFactory factory) {
		l = Logger.getLogger(this.getClass());
		this.eqToRemove=eqToRemove;
		this.factory=factory;
	}

	public synchronized void run() {
		Transaction tx =null;
		Session session = null;
		if(factory!=null)
			while(true){
				try{
					int num=0;
					do{
						byte[] object=eqToRemove.take();
						eqToRemove.remove(object);
						if(object!=null){
							if((session==null) || (!session.isOpen()))
								session=factory.openSession();
							if((tx == null) || (!tx.isActive()))
								tx=session.beginTransaction();
							Query query = session.createQuery(QUERY_RAWDATA);
							query.setBinary(0, object);
							query.setMaxResults(1);
							//l.info("Hibernate: "+QUERY_RAWDATA+" --[ "+new String(object)+" ]");
							Object ob = query.uniqueResult();
							if(ob!=null){
								num++;
								session.delete(ob);
							}
							else
								l.error(ERROR_RAWDATA);
						}
					}while(eqToRemove.size()>0);

					if (tx != null && tx.isActive())
						tx.commit();
					//l.info(INFO_DELETE +" ("+num+")");

				} catch (InterruptedException e) {
					l.error(e.getMessage());
				} catch (RuntimeException e) {
					if (tx != null && tx.isActive()) {
						try {
							tx.rollback();
						} catch (HibernateException e1) {
							l.error(ERROR_ROLLING_BACK);
						}
						throw e;
					}
				}
				finally{
					if ((session!=null) && (session.isOpen())) 
						session.close(); 
				}
			}
	}
}
